using System.IO;
using UnityEngine.Networking;
namespace Framework
{
    //下载并写入文件
    public class FileStreamHandler : DownloadHandlerScript
    {
        public int Length { get; private set; }
        private int _contentLength;
        private FileStream _stream;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath">存储路径</param>
        /// <param name="buffer">交换数据的缓存</param>
        /// <returns></returns>
        public FileStreamHandler(string filePath, byte[] buffer) : base(buffer)
        {
            _stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
        }
        #if UNITY_2021_1_OR_NEWER
        public override void Dispose()
        {
            base.Dispose();
            if (_stream != null)
            {
                _stream.Flush();
                _stream.Close();
                _stream.Dispose();
                _stream = null;
            }
        }
        #endif
        protected override bool ReceiveData(byte[] data, int dataLength)
        {
            if (data == null || data.Length < 1)
            {
                return false;
            }
            _stream.Write(data, 0, dataLength);
            Length += dataLength;
            return true;
        }
        protected override byte[] GetData()
        {
            return null;
        }
        protected override void ReceiveContentLengthHeader(ulong contentLength)
        {
            _contentLength = (int)contentLength;
        }
        protected override void CompleteContent()
        {
            _stream.Flush();
            _stream.Close();
            _stream.Dispose();
            _stream = null;
        }
        protected override float GetProgress()
        {
            if (_contentLength < 1) return 0f;
            return (float)Length / (float)_contentLength;
        }
    }
}